package com.tobe.spring_demo.mybatis;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

/**
 * spring 比这里更加自动化,
 * mapper interface 对应 MapperFactoryBean<> , 而且泛型也是通过beanDenifition设置
 * @author yangqifan 2015年9月14日
 * 
 */
public class MyMapperFactoryBean<T> implements FactoryBean<T>, InitializingBean{
	
	private A a;
	
	//
	private Class<T> mapperInterface;
	
	//
	public MyMapperFactoryBean(Class<T> t){
		this.mapperInterface = t;
	}
	
	//这样设置构造函数参数,spring构建实例的时候会自动转换
	//definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName());
//	public MyMapperFactoryBean(String name){
//		System.out.println("name = " + name);
//	}
	
	public void setAbbbb(A a){
		//bean a在bean b之前已经创建
		System.out.println("call set方法, 因为该beanDefiniton.autoWireByType, 如果容器中有 A类型的bean, 如果没有不会调用该方法 ");
		//只要方法名以set开头+方法参数class type, 就可以注入了
		this.a = a;
	}
	
	public void setMapperInterface(Class<T> mapperInterface) {
		//MapperFactoryBean中的泛型class
		this.mapperInterface = mapperInterface;
		System.out.println("设置Class<A>");
	}

	public T getObject() throws Exception {
		return (T) new MyMapperFactoryBean(mapperInterface);
	}

	public Class<?> getObjectType() {
		return MyMapperFactoryBean.class;
	}

	public boolean isSingleton() {
		return false;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		//bean 检查
		Assert.notNull(a, "A 类型的bean没有找到, 检查配置");
		Assert.notNull(mapperInterface, "mapperInterface 类型的bean没有找到, 检查配置");
		
		System.out.println("mapperInterface = " + mapperInterface);
	}

}

